// grid和布局的全局变量
var sm;
var cm;
var store;
var grid;
var viewport;
var currentRowInd = 0;
var currentColInd;
var Plant;
var field_currentRow;
Ext.onReady(function () {
    Ext.QuickTips.init();
    var sm = new Ext.grid.CheckboxSelectionModel();
    var column_align_json = new Ext.data.SimpleStore({
        fields: ['value', 'name'],
        data: [['left', 'left'], ['center', 'center'], ['right', 'right']]
    });
    var combo = new Ext.form.ComboBox({
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 0,
            fields: [
                'myId',
                'displayText'
            ],
            data: [[true, '可空'], [false, '非空']]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    });
    var combo1 = new Ext.form.ComboBox({
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 1,
            fields: [
                'myId',
                'displayText'
            ],
            data: [[true, '隐藏'], [false, '不隐藏']]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    });
    var combo3 = new Ext.form.ComboBox({
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 3,
            fields: [
                'myId',
                'displayText'
            ],
            data: [[true, '排序'], [false, '不排序']]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    });
//    var combo7 = new Ext.form.ComboBox({
//        typeAhead: true,
//        triggerAction: 'all',
//        lazyRender: true,
//        mode: 'local',
//        store: new Ext.data.ArrayStore({
//            id: 7,
//            fields: [
//                'myId',
//                'displayText'
//            ],
//            data: [[true, '显示'], [false, '不显示']]
//        }),
//        valueField: 'myId',
//        displayField: 'displayText'
//    });
    var combo5 = new Ext.form.ComboBox({
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 4,
            fields: [
                'myId',
                'displayText'
            ],
            data: [['db', '数据库字段'], ['virtual', '虚拟字段']]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    });
    var combo6 = new Ext.form.ComboBox({
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 6,
            fields: [
                'myId',
                'displayText'
            ],
            data: [['redis', 'redis'], ['image', '图片'], ['detail', '物料详情']]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    });
    //sm.handleMouseDown = Ext.emptyFn;//不响应MouseDown事件
    cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), sm, {
        header: 'ID',
        dataIndex: 'id',
        hidden: true,
        width: 10
    }, {
        header: '表格字段',
        dataIndex: 'column_lable',
        editor: new Ext.form.TextField({
            allowBlank: false,
            blankText: "不允许为空"
        }),
        width: 100
    }, {
        header: '数据库字段',
        dataIndex: 'db_column_lable',
        width: 100
    }, {
        header: '标题',
        dataIndex: 'column_title',
        editor: new Ext.form.TextField(),
        width: 120
    }, {
        header: '默认值',
        dataIndex: "default_value",
        menuDisabled: true,
        width: 140,
        hidden: true,
        editor: new Ext.form.TextField({
            id: 'DEFAULTVALUE',
            name: 'DEFAULTVALUE',
            selectOnFocus: true,
            autoShow: true
        })
    }, {
        header: '数据映射类型',
        dataIndex: 'ref_type',
        editor: combo6,
        renderer: Ext.util.Format.comboRenderer(combo6),
        width: 100
    }, {
        header: '数据映射',
        dataIndex: 'ref_params',
        editor: new Ext.grid.GridEditor(new Ext.form.TextField()),
        width: 170
    }, {
        //xtype : 'checkcolumn',
        header: '允许空',
        dataIndex: 'is_null',
        width: 55,
        editor: combo,
        renderer: Ext.util.Format.comboRenderer(combo)
    }, {
        //xtype : 'checkcolumn',
        header: '是否隐藏',
        dataIndex: 'hidden',
        width: 55,
        editor: combo1,
        hidden: is_master_dataset,
        renderer: Ext.util.Format.comboRenderer(combo1)
    }, 
//    {
//        //xtype : 'checkcolumn',
//        header: '是否展示详情',
//        dataIndex: 'showdetails',
//        width: 55,
//        editor: combo7,
//        hidden: is_master_dataset,
//        renderer: Ext.util.Format.comboRenderer(combo7)
//    },
    {
        //xtype : 'checkcolumn',
        header: '是否排序',
        dataIndex: 'sortable',
        width: 55,
        hidden: is_master_dataset,
        editor: combo3,
        renderer: Ext.util.Format.comboRenderer(combo3)
    }, {
        //xtype : 'checkcolumn',
        header: '字段类型',
        dataIndex: 'column_type',
        width: 55,
        //editor: combo5,
        renderer: Ext.util.Format.comboRenderer(combo5)
    }, {
        header: '对齐数据',
        dataIndex: 'column_align',
        width: 80,
        hidden: is_master_dataset,
        editor: new Ext.form.ComboBox({
            hideLabel: true,
            lazyRender: true, // 值为true时阻止ComboBox渲染直到该对象被请求
            store: column_align_json,
            displayField: "name",
            valueField: "value",
            mode: "local",
            editable: false,
            triggerAction: "all"

        }),
    }, {
        header: '格式化函数',
        dataIndex: 'formatter',
        width: 170,
        hidden: is_master_dataset,
        editor: new Ext.grid.GridEditor(new Ext.form.TextArea())
    }, {
        header: '表单UI',
        dataIndex: 'ui_type',
        renderer: renderer_ui,
        hidden: !is_master_dataset,
        width: 80
    }, {
        header: 'ui_param',
        dataIndex: 'ui_param',
        hidden: true,
        width: 80
    }, {
        header: 'order_index',
        dataIndex: 'order_index',
        hidden: true,
        width: 80
    }]);
    Plant = Ext.data.Record.create([{
        name: 'id',
        type: 'string'
    }, {
        name: 'column_lable',
        type: 'string'
    }, {
        name: 'db_column_lable',
        type: 'string'
    }, {
        name: 'column_title',
        type: 'string'
    }, {
        name: 'default_value',
        type: 'string'
    }, {
        name: 'is_null',
        type: 'bool'
    }, {
        name: 'column_type',
        type: 'string'
    }, {
        name: 'ui_type',
        type: 'string'
    }, {
        name: 'ui_param',
        type: 'string'
    }, {
        name: 'order_index',
        type: 'int'
    }, {
        name: 'hidden',
        type: 'bool'
    },
//    {
//        name: 'showdetails', 
//        type: 'bool'
//    }, 
    {
        name: 'sortable', 
        type: 'bool'
    }, {
        name: 'column_align',
        type: 'string'
    }, {
        name: 'ref_type',
        type: 'string'
    }, {
        name: 'ref_params',
        type: 'string'
    }, {
        name: 'formatter',
        type: 'string'
    }]);

    store = new Ext.data.Store({
        baseParams: {
            form_id: form_id,
            formMetadataId: formMetadataId
        },
        proxy: new Ext.data.HttpProxy({
            url: basePath + 'repository/form/metadatamap/getFormMeatadataJson'
        }),
        reader: new Ext.data.JsonReader({
            totalProperty: "total",
            root: "root",
            id: "id"
        }, ['id', 'column_title', 'column_lable', 'db_column_lable', 'column_type', 'default_value', 'is_null', 'ui_type', 'ui_param', 'order_index', 'hidden', 'sortable', 'column_align', 'formatter', 'ref_params', 'ref_type'], Plant)
    });
    grid = new Ext.grid.EditorGridPanel({
        renderTo: 'grid',
        store: store,
        region: 'center',
        cm: cm,
        sm: sm,
        trackMouseOver: false,
        clicksToEdit: 1,
        loadMask: {
            msg: '正在加载数据，请稍候...'
        },
        border: false,
        enableDragDrop: true,
        viewConfig: {
            forceFit: true
        },
        listeners: {
            'bodyscroll': function () {
                return false;
            }
        },
        tbar: [{
            text: '添加数据库字段',
            iconCls: 'iconNew',
            handler: function () {
                parent.openFormMetadatMapWin(formMetadataName, formMetadataId);
            }
        }, '-', {
            text: '添加虚拟字段',
            iconCls: 'iconNew',
            handler: function () {
                addVirtualField(formMetadataName, formMetadataId);
            }
        }, '-', {
            text: '保存',
            iconCls: 'iconSave',
            handler: function () {
                saveGrid();
            }
        }, '-', {
            text: '删除',
            iconCls: 'iconDelete',
            id: "deleteC",
            disabled: true,
            handler: function () {
                remove();
            }
        }, '-', {
            text: '刷新',
            tooltip: '刷新',
            handler: function () {
                store.reload();
            },
            iconCls: 'iconRefresh'
        }, '-', {
            text: '重新排序',
            tooltip: '重新排序',
            handler: function () {
                Ext.Ajax.request({
                    url: basePath + 'repository/form/metadatamap/afreshSortFormMetadataMap',
                    method: 'POST',
                    params: {
                    	form_id: form_id,
                    	formMetadataId:formMetadataId
                    },
                    failure: function (response, options) {
                        Ext.MessageBox.alert('操作失败', '操作失败！可能是网络超时！');
                        return false;
                    },
                    success: function (response, options) {
                        if (response.responseText == 'ok') {
                            Ext.MessageBox.alert('提示', " 重新排序成功! ");
                            store.reload();
                        } else {
                            Ext.MessageBox.alert('提示', " 重新排序失败!! ");
                            return false;
                        }
                    }
                });
            },
            iconCls: 'iconRefresh'
        }, '->']
    });
    viewport = new Ext.Viewport({
        layout: 'border',
        items: [grid]
    });
    store.load();
    grid.addListener('cellmousedown', handleGridMove);
    function handleGridMove(o, r, c) {
        currentRowInd = r;
        currentColInd = c;
        return;
    }

    grid.on("beforeedit", function (e) {
        // e.record.id
        if (e.field == 'COLUMN_NAME' && e.record.data.ID != '') {
            e.cancel = true;
        }
    }, this);
    grid.on("afteredit", function (e) {
        if (e.field == 'COLUMN_TYPE') {
            var column_type = e.record.get('COLUMN_TYPE');
            if (column_type == '日期') {
                e.record.set('COLUMN_LENGTH', '');
            }
        }
    }, this);
    grid.on('cellclick', function (grid, rowIndex, columnIndex, e) {
        if (columnIndex == 5) {
            field_currentRow = grid.getStore().getAt(rowIndex);
        }
    });
    if (!is_master_dataset) {
        grid.getTopToolbar().addText('<b>是否展示详情：</b>');
        grid.getTopToolbar().addText(is_detail_html);
//        grid.getTopToolbar().addText('<b>详情字段：</b>');
//        grid.getTopToolbar().addText(details_field_html);
    }
    if (!is_master_dataset) {
        grid.getTopToolbar().addText('<b>是否分组显示：</b>');
        grid.getTopToolbar().addText(is_group_html);
        grid.getTopToolbar().addText('<b>分组字段：</b>');
        grid.getTopToolbar().addText(group_field_html);
    }
    grid.getSelectionModel().on('selectionchange', function (t) {
        Ext.getCmp("deleteC").setDisabled(t.getSelections().length === 0);
    });
    var ddrow = new Ext.dd.DropTarget(grid.container, {
        ddGroup: 'GridDD',
        copy: false,
        notifyDrop: function (dd, e, data) {
            var rows = data.selections;
            //data.rowIndex
            //var index = dd.getDragData(e).rowIndex;
            if (dd.getDragData(e).rowIndex == undefined) {
                return;
            }
            var sourceId = rows[0].id;
            var targetId = dd.getDragData(e).selections[0].id;
            handleSave(sourceId, targetId);
            return;
        }
    });
});

function renderer_data(value, cell, record, rowIndex, columnIndex, store) {

    var ref_type = record.data.ref_type;
    var ref_params = record.data.ref_params;
    var ref_type_title = ref_type == null || ref_type == '' ? '--' : ref_type;
    var val = '<a href=\'javascript:void(0)\' onclick="openDataRefDesignDialog(\'' + ref_type + '\',\'' + ref_params + '\');">' + ref_type_title + '</a>';
    return val;
}
function addVirtualField(formMetadataName, formMetadataId) {
    var datasetUrl = basePath + 'repository/form/metadatamap/openVirtualFormMetadataMapPage?form_id=' + form_id + '&formMetadataId=' + formMetadataId;
    openSimpleExtWindow('添加虚拟字段', 500, 270, datasetUrl);
    if (activeDialog) {
        activeDialog.purgeListeners();
        activeDialog.addListener('show', handleShow);
        activeDialog.addListener('beforehide', handleHide);
        activeDialog.show();
    }
}
function saveGrid() {
    var zbfyys = 0;
    var gridheight = 0;
    var is_group_value = false;
    var group_field_value = '';
    var is_detail_value=false;
//    var detail_field_value='';
    if (!is_master_dataset) {
        var group_obj = document.getElementById('is_group');
        if (group_obj.checked) {
            is_group_value = true;
        }
        group_field_value = document.getElementById('group_field').value;
        
        var detail_obj = document.getElementById('is_detail');
        if (detail_obj.checked) {
            is_detail_value = true;
        }
//        detail_field_value = document.getElementById('detail_field').value;
    }
    var m = store.getModifiedRecords();
    if (m.length > 0 || !is_master_dataset) {
        for (var i = 0, len = m.length; i < len; i++) {
            var rec = m[i];
        }
        var temp = 0;
        var json = [];
        Ext.each(m, function (item) {
            json.push(item.data);
        });
        store.commitChanges();
        Ext.Ajax.request({
            url: basePath + 'repository/form/metadatamap/saveFormMetadataMap',
            method: 'POST',
            params: {
                datas: Ext.util.JSON.encode(json),
                grid_height: (gridheight == "" ? 0 : gridheight),
                page_size: zbfyys,
                formMetadataId: formMetadataId,
                form_id: form_id,
                is_group: is_group_value,
                group_field: group_field_value,
                is_detail: is_detail_value
//                detail_field: detail_field_value
            },
            failure: function (response, options) {
                Ext.MessageBox.alert('操作失败', '操作失败！可能是网络超时！');
                return false;
            },
            success: function (response, options) {
                if (response.responseText == 'ok') {
                    Ext.MessageBox.alert('提示', " 保 存 成 功! ");
                    store.reload();
                } else {
                    Ext.MessageBox.alert('提示', " 保 存 失 败! ");
                    return false;
                }
            }
        });
    } else {
        Ext.MessageBox.alert('提示', '当前没有需要保存的记录!');
        return false;
    }
}

function remove() {
    var selectedKeys = grid.selModel.selections.keys;
    Ext.MessageBox.confirm('提示', '确定删除选定的字段?', function (btn) {
        if (btn == 'yes') {
            Ext.Ajax.request({
                url: basePath + 'repository/form/metadatamap/removeFormMetadataMap',
                method: 'POST',
                params: {
                    ids: selectedKeys,
                    formMetadataId: formMetadataId,
                    form_id: form_id
                },
                failure: function (response, options) {
                    Ext.MessageBox.alert('操作失败', '操作失败！可能是网络超时！');
                    return false;
                },
                success: function (response, options) {
                    if (response.responseText == 'ok') {
                        store.commitChanges();
                        store.reload();
                        Ext.MessageBox.alert('提示', " 删 除 成 功! ");
                    }
                }
            });
        }

    });
}

function reflashGrid() {
    store.reload();
}

function renderer_ui(value, cell, record, rowIndex, columnIndex, store) {
    var clolumnId = record.data.id;
    var column_title = record.data.column_title;
    var column_lable = record.data.column_lable;
    var ui_type = record.data.ui_type;
    var val = '<a href=\'javascript:void(0)\' onclick="parent.changeUi(' + rowIndex + ');">' + ui_type + '</a>';
    return val;
}
function settingUiComponentParams(uiRowIndex, ui_type, ui_param) {
    var record = grid.getStore().getAt(uiRowIndex);
    record.set('ui_type', ui_type);
    record.set('ui_param', ui_param);
    parent.uiWindow.close();
}
function handleSave(sourceId, targetId) {
    Ext.getBody().mask("保存排序...");
    Ext.Ajax.request({
        url: basePath + 'repository/form/metadatamap/sortGird',
        method: 'POST',
        params: {
            sourceId: sourceId,
            targetId: targetId,
            form_id: form_id,
            form_er_id: formMetadataId
        },
        failure: function (response, options) {
            Ext.MessageBox.alert('操作失败', '操作失败！可能是网络超时！');
            return false;
        },
        success: function (response, options) {
            Ext.getBody().unmask();
            if (response.responseText != '1') {
                Ext.MessageBox.alert('提示', " 排序发生错误，请刷新重新重试! ");
            } else {
                store.reload();
            }
        }
    });
}
Ext.util.Format.comboRenderer = function (combo) {
    return function (value) {
        var record = combo.findRecord(combo.valueField, value);
        return record ? record.get(combo.displayField) : combo.valueNotFoundText;
    }
}

function tableReload() {
    store.reload();
}